package com.rupeng.web.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rupeng.pojo.User;
import com.rupeng.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.rupeng.pojo.Setting;
import com.rupeng.service.SettingService;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Controller
public class OtherController {
	@Autowired
	SettingService settingService;
	@RequestMapping("/")
	public ModelAndView index() {
		return new ModelAndView("index");
	}
	@RequestMapping("/imageCode.do")
	public void imageCode(HttpServletRequest request, HttpServletResponse response) {
		ImageCodeUtils.sendImageCode(request.getSession(), response);
	}
	@RequestMapping("/smsCode.do")
	public @ResponseBody AjaxResult smsCode(String phone, HttpServletRequest request, HttpServletResponse response) {
        if (CommonUtils.isEmpty(phone)) {
            return AjaxResult.errorInstance("手机号不能为空");
        }
        if (!CommonUtils.isPhone(phone)) {
            return AjaxResult.errorInstance("您输入的手机号不符合手机号格式");
        }
        Setting url = settingService.selectOneByName("sms_url_code");
        Setting appSecret = settingService.selectOneByName("sms_app_secret");
        Setting appKey = settingService.selectOneByName("sms_app_key");
        Setting templateId = settingService.selectOneByName("sms_code_template");
        SMSUtils.sendSMSCode(request.getSession(), url.getValue(), appKey.getValue(), appSecret.getValue(), templateId.getValue(), phone);
        return AjaxResult.successInstance("发送成功");
    }
	@RequestMapping("/emailCode.do")
	public @ResponseBody AjaxResult emailCode(String email, HttpServletRequest request, HttpServletResponse response) {
		if (CommonUtils.isEmpty(email)) {
            return AjaxResult.errorInstance("邮箱不能为空");
        }
        if (!CommonUtils.isEmail(email)) {
            return AjaxResult.errorInstance("您输入的邮箱不符合邮箱格式");
        }
		Setting smtpHost = settingService.selectOneByName("email_smtp_host");
		Setting username = settingService.selectOneByName("email_username");
		Setting password = settingService.selectOneByName("email_password");
		Setting from = settingService.selectOneByName("email_from");
		EmailUtils.sendEmailCode(request.getSession(), smtpHost.getValue(), username.getValue(), password.getValue(), from.getValue(), email, true);
		return AjaxResult.successInstance("发送成功");
	}
	@RequestMapping("/notification.do")
	public @ResponseBody AjaxResult notificationList(HttpServletRequest request){
		User user = (User)request.getSession().getAttribute("user");
		if (user==null) {
			return AjaxResult.errorInstance("您还没有登陆");
		}
		//获取当前用户所有通知消息，并且把通知消息从redis里面删除掉
		Set<String> datas = JedisUtils.smembersAndDel("notification_"+user.getId());
		if (CommonUtils.isEmpty(datas)){
			return AjaxResult.successInstance(null);
		}
		List<Object> list = new ArrayList<>();
		for (String string : datas){
			Object obj = JsonUtils.toBean(string, Object.class);
			list.add(obj);
		}
		return AjaxResult.successInstance(list);
	}
	@RequestMapping(value="/upload.do",method=RequestMethod.GET)
	public ModelAndView uploadConfig(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/lib/ueditor/jsp/config.json").forward(request,response);
		return null;
	}
	@RequestMapping(value="/upload.do",method = RequestMethod.POST)
	public @ResponseBody Map<String, String> uploadSubmit(MultipartFile upfile) throws IOException {
		InputStream inputStream = upfile.getInputStream();
		Calendar date = Calendar.getInstance();
		date.setTime(new Date());
		String fileMD5 = CommonUtils.calculateMD5(inputStream)+UploadUtils.getExtension(upfile.getOriginalFilename());
		inputStream.close();
		String fileName = date.get(Calendar.YEAR)+"/"+(date.get(Calendar.MONTH)+1)+"/"+date.get(Calendar.DAY_OF_MONTH)+"/"+fileMD5;
		Setting accessKeyId = settingService.selectOneByName("aliyun_accessKeyId");
		Setting accessKeySecret = settingService.selectOneByName("aliyun_accessKeySecret");
		Setting bucketName = settingService.selectOneByName("aliyun_upload_bucketName");
		inputStream = upfile.getInputStream();
		UploadUtils.uploadWithAliyun(inputStream,fileName,accessKeyId.getValue(),accessKeySecret.getValue(),bucketName.getValue());
		inputStream.close();
		Map<String, String> result = new HashMap<String, String>();
		result.put("state","SUCCESS");
		result.put("original", upfile.getOriginalFilename());
		result.put("title", fileMD5);
		result.put("type", UploadUtils.getExtension(upfile.getOriginalFilename()));
		result.put("url", "/"+fileName);
		return result;
	}
}
